<template>
  <div class="mx-auto w-[380px] flex flex-col justify-center items-center gap-4">
    <div id="express-checkout-element" class="w-full h-[55px]"></div>
<!--    <div id="link-authentication-element" class="w-full"></div>-->
    <div id="payment-element" class="w-full"></div>
    <a-button type="primary" :loading="paying" block @click="payment">支付</a-button>
  </div>
</template>

<script setup lang="ts">
import { loadStripe, type Stripe, type StripeCheckout } from '@stripe/stripe-js'

let stripe: Stripe
let checkout: StripeCheckout
let clientSecret = ''

const init = async () => {
  await Promise.all([
    call(async () => {
      // 获取客户端密钥
      const res = await getStripeClientSecret.fetch({ mode: 'custom' })
      clientSecret = res?.data.clientSecret || ''
    }),
    call(async () => {
      // 加载 stripe
      stripe = (await loadStripe('pk_test_51R2tSZP8ixH7RW52Te77yDDQ5BfdJJRoXyGb3F8WUZiK1K901Sjf6D71ddqaBxQSRSsYUJhGiKdyz7iiUdouWiyM003J6WGXdv', {
        betas: ['custom_checkout_beta_5'],
      })) as Stripe
    }),
  ])

  checkout = await stripe.initCheckout({
    clientSecret,
  })
  checkout.on('change', (session) => {
    console.log('session', session)
    checkout.updateEmail('zcf.momoky@outlook.com')
  })


  const expressCheckoutElement = checkout.createElement('expressCheckout', {
    buttonHeight: 55,
    // paymentMethods:
  })
  /*expressCheckoutElement.update({
    defaultValues: {
      billingDetails: {
        name: 'John Doe',
        email: 'john.doe@example.com',
        address: {
          city: 'New York',
          country: 'US',
          line1: '123 Main St',
          postal_code: '10001',
          state: 'NY'
        }
      }
    }
  })*/
  expressCheckoutElement.mount('#express-checkout-element')

  const paymentElement = checkout.createElement('payment', {
    layout: 'accordion',
  })
  paymentElement.mount('#payment-element')
  /*paymentElement.update({
    defaultValues: {
      billingDetails: {
        name: 'John Doe',
        email: 'john.doe@example.com',
        address: {
          city: 'New York',
          country: 'US',
          line1: '123 Main St',
          postal_code: '10001',
          state: 'NY'
        }
      },
    }
  });*/
}

const paying = ref(false)
const payment = async () => {
  try {
    paying.value = true
    const res = await checkout.confirm({
      redirect: 'if_required',
    })
    if (res.type === 'success') {
      message.success('支付成功')
    }
  } finally {
    paying.value = false
  }
}

onMounted(init)
</script>
